/**
 * 
 */
package com.oauth.common.server.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oauth.logging.OAuthLogger;

/**
 * @author asanthan
 * 
 */
public class RapWavesRedirectFilter implements Filter {

	private static final String DOMAIN_NAME = "rapwaves.com";

	private OAuthLogger logger = OAuthLogger.getLogger(RapWavesRedirectFilter.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 * javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		if (!isValidHostName(httpRequest)) {
			logger.info(String.format("Found host=%s ,Redirecting....", httpRequest.getServerName()));
			httpResponse.sendRedirect("http://www.rapwaves.com/");
		} else {
			chain.doFilter(request, response);
		}

	}

	/**
	 * @param httpRequest
	 * @return
	 */
	private boolean isValidHostName(HttpServletRequest httpRequest) {
		return httpRequest.getServerName() != null
				&& httpRequest.getServerName().endsWith(DOMAIN_NAME);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}
